<script setup>
import { onMounted, onUnmounted, ref, nextTick } from 'vue';
import { initWebSocket, closeWebSocket, getDepartmentIcon } from '@/services/api.js';

const currentTime = ref('');
const currentDate = ref('');
// 删除默认数据，初始化为空
const currentCall = ref({ number: '', window: '', department: '' });
const numbers = ref([]);
// 删除硬编码的部门列表，改为动态获取
const departments = ref([]);
// 添加部门等候信息
const departmentWaitingInfo = ref([]);
// 添加窗口状态数据
const windowsStatus = ref([]);
const loading = ref(false);
// 添加等候队列数据
const waitingQueue = ref([]);
// 添加通知公告数据
const announcements = ref([]);
// 添加WebSocket连接状态
const wsConnected = ref(false);

function updateTime() {
    const now = new Date();
    const timeOptions = { hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false };
    const dateOptions = { year: 'numeric', month: 'long', day: 'numeric', weekday: 'long' };
    currentTime.value = now.toLocaleTimeString('zh-CN', timeOptions);
    currentDate.value = now.toLocaleDateString('zh-CN', dateOptions);
}

// 处理当前叫号信息更新 (dataType: 1)
function handleCurrentCallUpdate(data) {
  console.log('📞 收到当前叫号信息更新:', data);
  console.log('📞 数据类型:', typeof data, '是否为对象:', typeof data === 'object');
  console.log('📞 对象键值:', data ? Object.keys(data) : 'null');
  
  // 强制更新当前叫号信息
  if (data && typeof data === 'object') {
    const newCall = {
      number: data.currentTicketNo || data.ticketNo || '暂无叫号',
      window: data.counterName || data.windowName || '暂无窗口',
      department: data.departmentName || '暂无部门'
    };
    
    console.log('📞 更新前 currentCall:', JSON.stringify(currentCall.value));
    currentCall.value = newCall;
    console.log('📞 更新后 currentCall:', JSON.stringify(currentCall.value));
    
    // 强制Vue重新渲染
    nextTick(() => {
      console.log('📞 nextTick后 currentCall:', JSON.stringify(currentCall.value));
    });
  } else {
    console.log('📞 数据为空，设置默认值');
    currentCall.value = { 
      number: '暂无叫号', 
      window: '暂无窗口', 
      department: '暂无部门' 
    };
  }
}

// 处理窗口状态信息更新 (dataType: 2)
function handleWindowStatusUpdate(data) {
  console.log('🪟 收到窗口状态信息更新:', data);
  console.log('🪟 数据类型:', Array.isArray(data), '长度:', data ? data.length : 'null');
  
  if (Array.isArray(data)) {
    const newWindows = data.map((window, index) => {
      console.log(`🪟 处理窗口 ${index}:`, window);
      return {
        counterName: window.counterName || window.windowName || `窗口${index + 1}`,
        departmentName: window.departmentName || '未知部门',
        currentTicketNo: window.currentTicketNo || window.ticketNo || '',
        status: window.status || '0',
        statusText: getStatusText(window.status, window.currentTicketNo || window.ticketNo),
        statusClass: getStatusClass(window.status)
      };
    });
    
    console.log('🪟 更新前 windowsStatus:', JSON.stringify(windowsStatus.value));
    windowsStatus.value = newWindows;
    console.log('🪟 更新后 windowsStatus:', JSON.stringify(windowsStatus.value));
  } else {
    console.log('🪟 数据不是数组，清空窗口状态');
    windowsStatus.value = [];
  }
}

// 处理等待队列信息更新 (dataType: 3)
function handleWaitQueueUpdate(data) {
  console.log('⏳ 收到等待队列信息更新:', data);
  console.log('⏳ 数据类型:', Array.isArray(data), '长度:', data ? data.length : 'null');
  
  if (Array.isArray(data)) {
    const validQueue = data
      .filter(item => {
        const hasTicket = item.ticketNo && item.ticketNo !== '';
        console.log('⏳ 队列项:', item, '有效:', hasTicket);
        return hasTicket;
      })
      .slice(0, 6)
      .map(item => ({
        ticketNo: item.ticketNo,
        departmentName: item.departmentName || '未知部门'
      }));
    
    console.log('⏳ 更新前 waitingQueue:', JSON.stringify(waitingQueue.value));
    waitingQueue.value = validQueue;
    numbers.value = validQueue.map(item => item.ticketNo);
    console.log('⏳ 更新后 waitingQueue:', JSON.stringify(waitingQueue.value));
    console.log('⏳ 更新后 numbers:', JSON.stringify(numbers.value));
  } else {
    console.log('⏳ 数据不是数组，清空等待队列');
    waitingQueue.value = [];
    numbers.value = [];
  }
}

// 处理通知公告信息更新 (dataType: 4)
function handleAnnouncementsUpdate(data) {
  console.log('📢 收到通知公告信息更新:', data);
  console.log('📢 数据类型:', Array.isArray(data), '长度:', data ? data.length : 'null');
  
  if (Array.isArray(data)) {
    const newAnnouncements = data.slice(0, 3).map((item, index) => {
      console.log(`📢 处理公告 ${index}:`, item);
      return {
        title: item.noticeTitle || item.title || `公告${index + 1}`,
        date: item.startTime || item.date || new Date().toISOString().split('T')[0],
        id: item.noticeId || item.id || `announcement_${index}_${Date.now()}`
      };
    });
    
    console.log('📢 更新前 announcements:', JSON.stringify(announcements.value));
    announcements.value = newAnnouncements;
    console.log('📢 更新后 announcements:', JSON.stringify(announcements.value));
  } else {
    console.log('📢 数据不是数组，清空通知公告');
    announcements.value = [];
  }
}

// 处理部门等候信息更新 (dataType: 5)
function handleDepartmentUpdate(data) {
  console.log('📊 收到部门等候信息更新:', data);
  console.log('📊 数据类型:', Array.isArray(data), '长度:', data ? data.length : 'null');
  
  if (Array.isArray(data)) {
    const newDepartments = data.map((item, index) => {
      console.log(`📊 处理部门 ${index}:`, item);
      return {
        departmentId: item.departmentId || `dept_${index}`,
        departmentName: item.departmentName || `部门${index + 1}`,
        waitingCount: parseInt(item.waitingCount) || 0
      };
    });
    
    console.log('📊 更新前 departmentWaitingInfo:', JSON.stringify(departmentWaitingInfo.value));
    departmentWaitingInfo.value = newDepartments;
    
    // 更新部门列表
    const uniqueDepartments = [...new Set(newDepartments.map(item => item.departmentName).filter(name => name))];
    departments.value = uniqueDepartments;
    
    console.log('📊 更新后 departmentWaitingInfo:', JSON.stringify(departmentWaitingInfo.value));
    console.log('📊 更新后 departments:', JSON.stringify(departments.value));
  } else {
    console.log('📊 数据不是数组，清空部门信息');
    departmentWaitingInfo.value = [];
    departments.value = [];
  }
}

// 处理所有信息更新 (dataType: 0)
function handleAllDataUpdate(data) {
  console.log('🔄 收到所有信息更新:', data);
  console.log('🔄 数据结构:', data ? Object.keys(data) : 'null');
  
  if (data && typeof data === 'object') {
    // 处理当前叫号信息
    if (data.currentCallData !== undefined) {
      console.log('🔄 处理 currentCallData:', data.currentCallData);
      handleCurrentCallUpdate(data.currentCallData);
    }
    
    // 处理窗口状态信息
    if (data.currentWinData !== undefined) {
      console.log('🔄 处理 currentWinData:', data.currentWinData);
      handleWindowStatusUpdate(data.currentWinData);
    }
    
    // 处理等待队列信息
    if (data.currentWaitData !== undefined) {
      console.log('🔄 处理 currentWaitData:', data.currentWaitData);
      handleWaitQueueUpdate(data.currentWaitData);
    }
    
    // 处理通知公告信息
    if (data.currentNoiceData !== undefined) {
      console.log('🔄 处理 currentNoiceData:', data.currentNoiceData);
      handleAnnouncementsUpdate(data.currentNoiceData);
    }
    
    // 处理部门等候信息
    if (data.currentDeptWaitData !== undefined) {
      console.log('🔄 处理 currentDeptWaitData:', data.currentDeptWaitData);
      handleDepartmentUpdate(data.currentDeptWaitData);
    }
    
    // 强制Vue重新渲染
    nextTick(() => {
      console.log('🔄 所有数据处理完成，当前状态:');
      console.log('   currentCall:', JSON.stringify(currentCall.value));
      console.log('   windowsStatus长度:', windowsStatus.value.length);
      console.log('   waitingQueue长度:', waitingQueue.value.length);
      console.log('   announcements长度:', announcements.value.length);
      console.log('   departmentWaitingInfo长度:', departmentWaitingInfo.value.length);
    });
  } else {
    console.log('🔄 数据为空或格式错误');
  }
}

// 处理WebSocket错误
function handleWebSocketError(error) {
  console.error('❌ WebSocket连接错误:', error);
  wsConnected.value = false;
  loading.value = false;
}

// 处理WebSocket连接状态
function handleWebSocketConnect() {
  console.log('✅ WebSocket连接成功');
  wsConnected.value = true;
  loading.value = false;
}

function handleWebSocketDisconnect() {
  console.log('🔌 WebSocket连接断开');
  wsConnected.value = false;
}

// 获取部门的等候人数
function getDepartmentWaitingCount(departmentName) {
  const dept = departmentWaitingInfo.value.find(item => item.departmentName === departmentName);
  return dept ? dept.waitingCount : 0;
}

// 获取状态文本
function getStatusText(status, currentTicketNo) {
  if (status === '1' || status === 1 || (typeof status === 'string' && status.includes('办理'))) {
    return currentTicketNo ? `办理中: ${currentTicketNo}` : '办理中';
  } else if (status === '2' || status === 2 || (typeof status === 'string' && status.includes('暂停'))) {
    return '暂停服务';
  } else {
    return '等待中';
  }
}

// 获取状态样式类
function getStatusClass(status) {
  if (status === '1' || status === 1 || (typeof status === 'string' && status.includes('办理'))) {
    return 'active';
  } else if (status === '2' || status === 2 || (typeof status === 'string' && status.includes('暂停'))) {
    return 'paused';
  } else {
    return '';
  }
}

let timerId;

onMounted(() => {
    updateTime();
    timerId = setInterval(updateTime, 1000);
    
    loading.value = true;
    
    // 初始化WebSocket连接，设置各种数据类型的处理器
    const handlers = {
      0: handleAllDataUpdate,        // 所有信息
      1: handleCurrentCallUpdate,    // 当前叫号信息
      2: handleWindowStatusUpdate,   // 窗口状态信息
      3: handleWaitQueueUpdate,      // 等待队列信息
      4: handleAnnouncementsUpdate,  // 通知公告
      5: handleDepartmentUpdate      // 部门等候人数信息
    };
    
    initWebSocket(handlers, handleWebSocketError)
      .then(() => {
        handleWebSocketConnect();
      })
      .catch((error) => {
        handleWebSocketError(error);
      });
});

onUnmounted(() => {
    clearInterval(timerId);
    // 关闭WebSocket连接
    closeWebSocket();
});

function goDepartment(name) {
    alert(`您选择了 ${name}，将显示该部门的详细排队信息`);
}
</script>

<template>
    <div class="container">
        <header>
            <div class="logo">
                <i class="fas fa-university"></i>
                <span>智慧校园系统</span>
            </div>
            <div class="campus-title">智能校园服务中心</div>
            <div class="campus-subtitle">高效服务 · 便捷校园 · 师生满意</div>
        </header>
        
        <div class="datetime">
            <div class="date">{{ currentDate }}</div>
            <div class="time">{{ currentTime }}</div>
            <div class="ws-status" :class="{ 'connected': wsConnected, 'disconnected': !wsConnected }">
                <i :class="wsConnected ? 'fas fa-wifi' : 'fas fa-wifi-slash'"></i>
                {{ wsConnected ? '实时连接' : '连接断开' }}
            </div>
        </div>

        <main>
            <div class="call-section">
                <div class="section-title">
                    <i class="fas fa-user-check"></i>
                    当前服务
                </div>

                <!-- 当前叫号显示 -->
                <div v-if="currentCall.number && currentCall.number !== '暂无叫号'" class="current-call">
                    <div class="window-number">
                        <i class="fas fa-desktop"></i>
                        {{ currentCall.window || '服务窗口' }}
                    </div>
                    <div class="number">{{ currentCall.number }}</div>
                    <div class="window">{{ currentCall.department || '服务办理' }} | 请到窗口办理</div>
                </div>

                <!-- 窗口状态显示 -->
                <div v-for="window in windowsStatus" :key="window.counterName" v-if="window && window.currentTicketNo && window.status === '1'" class="current-call">
                    <div class="window-number">
                        <i class="fas fa-desktop"></i>
                        {{ window.counterName || '服务窗口' }}
                    </div>
                    <div class="number">{{ window.currentTicketNo }}</div>
                    <div class="window">{{ window.departmentName || '服务办理' }} | 请到窗口办理</div>
                </div>

                <!-- 无数据时显示 -->
                <div v-if="(!currentCall.number || currentCall.number === '暂无叫号') && windowsStatus.filter(w => w && w.currentTicketNo && w.status === '1').length === 0" class="current-call">
                    <div class="window-number">
                        <i class="fas fa-info-circle"></i>
                        暂无当前服务
                    </div>
                    <div class="number">-</div>
                    <div class="window">等待叫号中</div>
                </div>
            </div>

            <div class="side-section">
                <div class="section-title">
                    <i class="fas fa-clock"></i>
                    等候呼叫
                </div>
                
                <!-- 等候队列 -->
                <div class="queue-items">
                    <div v-for="item in waitingQueue" :key="item.ticketNo" class="queue-item" v-if="item">
                        <span><i class="fas fa-desktop"></i> {{ item.departmentName || '服务窗口' }}</span>
                        <span class="number">{{ item.ticketNo }}</span>
                    </div>
                    <!-- 如果没有等候数据，显示提示 -->
                    <div v-if="waitingQueue.length === 0 && !loading" class="queue-item">
                        <span><i class="fas fa-info-circle"></i> 暂无等候队列</span>
                        <span class="number">-</span>
                    </div>
                    <!-- 加载状态 -->
                    <div v-if="loading" class="queue-item">
                        <span><i class="fas fa-spinner fa-spin"></i> 加载中...</span>
                        <span class="number">获取数据中</span>
                    </div>
                </div>
                
                <!-- 温馨提示 -->
                <div class="ad-container">
                    <i class="fas fa-bullhorn"></i>
                    温馨提示：学生证办理需携带身份证和一寸照片，办公时间：周一至周五 9:00-16:30
                </div>
                
                <!-- 滚动公告 -->
                <div class="marquee">
                    <div class="marquee-content">
                        <i class="fas fa-info-circle"></i>
                        <span v-for="(announcement, index) in announcements" :key="announcement.id" v-if="announcement">
                            &nbsp;{{ announcement.title || `公告${index + 1}` }}&nbsp;&nbsp;|&nbsp;&nbsp;
                        </span>
                        <span v-if="announcements.length === 0">
                            &nbsp;重要通知：图书馆将于下周一起延长开放时间至晚上10点 &nbsp;&nbsp;|&nbsp;&nbsp;
                            校园卡服务中心已迁移至学生活动中心一楼 &nbsp;&nbsp;|&nbsp;&nbsp;
                            下学期选课系统将于12月1日上午9点开放 &nbsp;&nbsp;|&nbsp;&nbsp;
                            2024届毕业生信息核对请于11月30日前完成
                        </span>
                    </div>
                </div>
            </div>
        </main>
        
        <!-- 底部信息栏 -->
        <div class="campus-info">
            <div class="info-item">
                <i class="fas fa-clock"></i>
                <span>服务时间：周一至周五 8:30-17:30</span>
            </div>
            <div class="info-item">
                <i class="fas fa-phone"></i>
                <span>服务中心电话：0123-4567890</span>
            </div>
            <div class="info-item">
                <i class="fas fa-map-marker-alt"></i>
                <span>地点：行政楼一楼大厅</span>
            </div>
        </div>
    </div>
</template>

<style>
/* WebSocket状态指示器样式 */
.ws-status {
  font-size: 12px;
  padding: 4px 8px;
  border-radius: 4px;
  margin-top: 5px;
  display: inline-flex;
  align-items: center;
  gap: 5px;
}

.ws-status.connected {
  background-color: rgba(76, 175, 80, 0.2);
  color: #4CAF50;
}

.ws-status.disconnected {
  background-color: rgba(244, 67, 54, 0.2);
  color: #f44336;
}

.realtime-indicator {
  font-size: 12px;
  color: #4CAF50;
  display: flex;
  align-items: center;
  gap: 4px;
}
</style>


